﻿using Microsoft.AspNetCore.Mvc.Filters;
using Zhp.Common.Extention;

namespace Zhp.Api.ActionExtension
{
    /// <summary>
    /// IActionFilter,IAsyncActionFilter同时作用时会根据添加顺序依次先执行，所以这里封装统一走这一种不要再使用IActionFilter
    /// </summary>
    public class BaseActionFilter : Attribute, IAsyncActionFilter
    {

        protected HttpContext HttpContext;

        /// <summary>
        /// Action执行之前
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public virtual async Task OnActionExecuting(ActionExecutingContext context)
        {
            await Task.CompletedTask;
        }

        /// <summary>
        /// Action执行之后
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public virtual async Task OnActionExecuted(ActionExecutedContext context)
        {
            await Task.CompletedTask;
        }

        /// <summary>
        /// IActionFilter,IAsyncActionFilter同时作用时根据添加顺序依次先执行
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            await OnActionExecuting(context);
            if (context.Result == null)
            {
                var nextContext = await next();
                await OnActionExecuted(nextContext);
            }
        }
    }
}
